import { SET_MY_INFO, CLEAR_MY_INFO } from '@/constants/user'
import { getMyInfo } from '@/api/user'
import { typeUserInfo } from '../types/user'
import { Store_User, Action } from './types'

export const userReducer = (
  state: Store_User,
  action: Action<typeUserInfo>
):Store_User => {
  switch (action.type) {
    case SET_MY_INFO:
      return {
        loading: false,
        userInfo: action.data
      }
    case CLEAR_MY_INFO:
      return {
        loading: false
      }
    default:
      return { ...state }
  }
}

/**
 * 获取个人信息并保存
 * @param userInfo 用户信息
 */
export const setMyInfo = (userInfo?:typeUserInfo) => async(dispatch:any) => {
  try {
    let data:typeUserInfo|undefined = userInfo

    /* 如果没有传入用户信息，则从数据库获取 */
    if (!data) {
      const res = await getMyInfo()

      data = res.data
    }
    dispatch({
      type: SET_MY_INFO,
      data: data
    })
  } catch (err:any) {
    return Promise.reject(err)
  }
}

/**
 * 退出登录
 */
export const loginOut = () => (dispatch:any) => {
  localStorage.removeItem('token')
  dispatch({ type: CLEAR_MY_INFO })
}
